<script lang="ts" setup>
import { ref, reactive, onMounted, toRaw } from 'vue'
import dayjs from 'dayjs'
import { useI18n } from 'vue-i18n'
import { Message } from '@/utils/message'

import { _queryLogger } from '@/api/user'
import { LoggerItem } from '@/api/types'
import RePagination from '@/components/RePagination/index.vue'
// 导入 SVG 文件
import Chrome from '@/assets/img/logger/Chrome.svg'
import Firefox from '@/assets/img/logger/Firefox.svg'
import Safari from '@/assets/img/logger/Safari.svg'
import Edge from '@/assets/img/logger/Edge.svg'
import Opera from '@/assets/img/logger/Opera.svg'
const svgIcons = {
  Chrome,
  Firefox,
  Safari,
  Edge,
  Opera
}
const { t } = useI18n()
const queryInfo = reactive({
  keyword: '',
  pageNum: 1,
  pageSize: 20,
  total: 0
})
const formRef = ref()

const tableData = ref<LoggerItem[]>([])

onMounted(() => {
  search()
})

const search = () => {
  _queryLogger(queryInfo)
    .then(res => {
      tableData.value = res.data.list.map(item => {
        return {
          ...item,
          device: getDevice(item.userAgent),
          browser: getBrowser(item.userAgent)
        }
      })
      queryInfo.total = res.data.total
    })
    .catch(err => {
      Message.error(err.message)
    })
}

const getBrowser = (userAgent: string): string => {
  if (/edge|edg/i.test(userAgent)) {
    return 'Edge'
  } else if (/chrome|crios/i.test(userAgent)) {
    return 'Chrome'
  } else if (/firefox|fxios/i.test(userAgent)) {
    return 'Firefox'
  } else if (
    /safari/i.test(userAgent) &&
    !/chrome|crios|edg/i.test(userAgent)
  ) {
    return 'Safari'
  } else if (/opr|opera/i.test(userAgent)) {
    return 'Opera'
  } else {
    return '-'
  }
}

const getDevice = (userAgent: string): Object => {
  if (/postman|postmanruntime/i.test(userAgent)) {
    const postmanVersion =
      userAgent.match(/postmanruntime\/([\d.]+)/i)?.[1] || ''
    return {
      text: `Postman ${postmanVersion}`,
      icon: 'icon-Postman',
      color: '#ff6c37'
    }
  } else if (/macintosh|mac os x/i.test(userAgent)) {
    const macVersion =
      userAgent
        .match(/macintosh;.*?mac os x (\d+)_(\d+)_(\d+)/i)
        ?.slice(1)
        .join('.') || ''
    return {
      text: `macOS ${macVersion}`,
      icon: 'icon-macOS'
    }
  } else if (
    /windows nt 10.0;.*?version\/10\.0\.\d+.*?windowsnt 10\.0/i.test(userAgent)
  ) {
    // More specific check for Windows 11, as it also reports as Windows NT 10.0
    return {
      text: 'Windows 11',
      icon: 'icon-Windows',
      color: '#429ce3'
    }
  } else if (/windows nt 10.0/i.test(userAgent)) {
    return {
      text: 'Windows 10',
      icon: 'icon-Windows',
      color: '#429ce3'
    }
  } else if (/windows nt/i.test(userAgent)) {
    return {
      text: 'Windows (Other)',
      icon: 'icon-Windows',
      color: '#429ce3'
    }
  } else if (/mobile/i.test(userAgent)) {
    return {
      text: 'Mobile',
      icon: 'icon-Mobile'
    }
  } else {
    return {
      text: '-'
    }
  }
}

const reset = () => {
  formRef.value.resetFields()
}
</script>

<template>
  <div class="p-[20px]">
    <el-form
      ref="formRef"
      :inline="true"
      :model="queryInfo"
      class="search-form"
    >
      <el-form-item label="关键词" prop="keyword">
        <el-input
          v-model="queryInfo.keyword"
          placeholder="输入关键词搜索"
          clearable
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="reset">{{ t('button.resetText') }}</el-button>
        <el-button type="primary" @click="search">{{
          t('button.queryText')
        }}</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" max-height="calc(100vh - 245px)">
      <el-table-column label="序号" type="index" width="60" />
      <el-table-column label="操作名称" prop="name" width="200" />
      <el-table-column label="method" prop="method" width="100">
        <template #default="{ row }">
          <el-tag type="success">{{ row.method }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="url" prop="url" show-overflow-tooltip width="200">
        <template #default="{ row }">
          <div class="two-line-ellipsis">{{ row.url }}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="参数信息"
        prop="param"
        show-overflow-tooltip
        width="200"
      >
        <template #default="{ row }">
          <div class="two-line-ellipsis">{{ row.param }}</div>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="statusCode" width="80">
        <template #default="{ row }">
          <el-tag :type="row.statusCode === 0 ? 'success' : 'danger'">{{
            row.statusCode === 0 ? '成功' : '失败'
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="异常信息"
        prop="responseData"
        show-overflow-tooltip
        width="200"
      >
        <template #default="{ row }">
          <div class="two-line-ellipsis">
            {{ row.statusCode !== 0 ? row.responseData : '' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="响应时长" prop="responseTime" width="100" />
      <el-table-column label="操作系统" prop="device" width="160">
        <template #default="{ row }">
          <i
            :class="[row.device.icon, 'mr-[8px]']"
            :style="{ color: row.device.color }"
          />{{ row.device.text }}
        </template>
      </el-table-column>
      <el-table-column label="浏览器" prop="browser" width="140">
        <template #default="{ row }">
          <component
            :is="toRaw(svgIcons[row.browser])"
            width="20"
            height="20"
            class="browser-icon"
          />{{ row.browser }}
        </template>
      </el-table-column>
      <el-table-column label="ip" prop="ip" width="100" />
      <el-table-column
        label="操作人"
        prop="userName"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column label="userId" prop="userId" width="90" />
      <el-table-column label="创建时间" prop="createTime" width="160">
        <template #default="{ row }">
          {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column>
    </el-table>

    <RePagination
      v-model:current="queryInfo.pageNum"
      v-model:page-size="queryInfo.pageSize"
      :total="queryInfo.total"
      @change="search"
    />
  </div>
</template>

<style lang="scss" scoped>
.browser-icon {
  display: inline-block;
  margin-right: 8px;
  vertical-align: sub;
}
</style>
